<template>
	<view class="main-content">
		<MHeader>{{ state.pageName }}</MHeader>
		<scroll-view scroll-y="true" style="height: calc(100% - 180rpx)">
			<view>
				<item name="组织" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_OrgName" disabled />
					<!-- <input class="input" v-model="state.info.Data.Model.F_QUQY_OrgName" placeholder="请选择" @click.native="choose('ORG_Organizations', 'F_QUQY_OrgId', 'FNumber', 'F_QUQY_OrgName', 'FNumber', 'FName')" /> -->
				</item>
				<item name="日期" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_Date" @click="chooseT('F_QUQY_Date')" placeholder="请选择" />
				</item>
				<item name="养殖批次" sign must>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_BreedingContractName" placeholder="请选择" @click.native="choose('BAS_PreBaseDataOne','F_QUQY_BreedingContract','FNUMBER','F_QUQY_BreedingContractName','FNumber','FName')" />
				</item>
				<item name="客户">
					<input class="input" v-model="state.info.Data.Model.F_QUQY_CustomerName" disabled placeholder="养殖批次带出" />
				</item>
				<item name="技术员" sign>
					<input class="input" v-model="state.info.Data.Model.F_QUQY_TechnicianName" placeholder="请选择" @click.native="choose('BD_Empinfo','F_QUQY_Technician','FSTAFFNUMBER','F_QUQY_TechnicianName','FNumber','FName')" />
				</item>
				<item name="是否退药">
					<van-switch v-model="state.info.Data.Model.F_QUQY_DrugRepercussion" size="24" @change="changeSwitch"></van-switch>
				</item>
				<item name="是否公司药">
					<van-switch v-model="state.info.Data.Model.F_QUQY_IsCompany" size="24"></van-switch>
				</item>
			</view>
			<MHeader hidTag>
				<van-icon name="cluster" color="#1989fa" style="margin-right: 10rpx" />
				兽药列表
				<template #right>
					<van-icon name="add-o" size="20" @click="appendItem" />
				</template>
			</MHeader>
			<view style="padding-bottom: 10rpx">
				<view class="card" v-for="(item, index) in state.info.Data.Model.FEntity">
					<view class="card-index">{{ index + 1 }}</view>
					<item name="兽药" sign must @longpress="longpress(item, index)">
						<input class="input" v-model="item.F_QUQY_MaterialName" placeholder="请选择" @click.native="choose('BD_MATERIAL','F_QUQY_Material','FNUMBER','F_QUQY_MaterialName','FNumber','FName','101204,102799,102800,102801',null,item)" />
					</item>
					<item name="库存单位">
						<input class="input" v-model="item.F_QUQY_UnitIDName" disabled placeholder="自动带出" />
					</item>
					<item name="仓库">
						<input class="input" v-model="item.F_QUQY_WarehouseName" disabled placeholder="自动带出" />
					</item>
					<van-field v-model="item.F_QUQY_RealQty" type="number" label="实发数量" placeholder="请输入" @update:model-value="qtyChange(item)" input-align="right"/>
					<!-- <item name="实发数量">
						<input class="input" v-model="item.F_QUQY_RealQty" type="number" placeholder="请输入" @input="qtyChange(item,$event)" />
					</item> -->
						<van-field v-model="item.F_QUQY_UnitPrice" type="number" label="含税单价" placeholder="请输入" @update:model-value="priceChange(item)" input-align="right">
							<template #extra>
								<text class="field-Input-Right-Text">元</text>
							</template>
						</van-field>
					<!-- <item name="含税单价">
						<input class="input" v-model="item.F_QUQY_UnitPrice" type="number" placeholder="请输入" style="padding-right: 35rpx" @input="priceChange(item,$event)" />
						<text class="symbol">元</text>
					</item> -->
					<item name="金额">
						<input class="input" v-model="item.F_QUQY_Amount" type="number" disabled placeholder="自动计算" style="padding-right: 35rpx" />
						<text class="symbol">元</text>
					</item>
				</view>
			</view>
		</scroll-view>
		<view class="btns">
			<van-button type="primary" size="small" @click="save">保 存</van-button>
			<view class="sum">
				合计：{{state.info.Data.Model.FEntity.reduce((preV,next)=>preV+Number(next.F_QUQY_Amount),0)}}元
			</view>
		</view>
	</view>
	<ChooseTime ref="chooseTime" />
	<Loading v-if="state.loading"></Loading>
</template>

<script setup>
	import moment from 'moment'
	import { reactive, getCurrentInstance, ref, watch, nextTick } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { checkForm } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import { confirm, msg } from '/utils/utils.js'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		info: {
			FormId: 'QUQY_DrugOutbound',
			Data: {
				Model: {
					F_QUQY_DrugRepercussion: false,
					F_QUQY_IsCompany: true,
					FEntity: [],
					F_QUQY_OrgId: {
						FNumber: null
					},
					F_QUQY_BreedingContract: {
						FNUMBER: null
					},
					F_QUQY_Customer: {
						FNUMBER: null
					},
					F_QUQY_Technician: {
						FSTAFFNUMBER: null
					}
				}
			}
		},
		rules: {
			F_QUQY_BreedingContractName: '请选择养殖批次！'
		},
		pageName: '兽药出库',
		memberInfo: null,
		F_QUQY_Warehouse: {
			FNUMBER: null
		},
		F_QUQY_WarehouseName: null,
		loading: true
	})

	const chooseTime = ref(null)
	const chooseT = (fieldName) => {
		chooseTime.value.start(state.info.Data.Model, fieldName)
	}
	// 1.组织控制（使用组织为当前选择的组织）：养殖批次
	const choose = (FormId, Field, FieldSon, FieldName, IdKey, IdKeyName, Group, BringOther, row) => {
		// 🐟 1
		let mustHasOrg = []
		if (mustHasOrg.includes(Field)) {
			if (!state.info.Data.Model.F_QUQY_OrgIdName) return msg('请先选择养殖批次！')
		}

		let FR = []
		if (Field == 'F_QUQY_Material') {
			FR = [{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: state.memberInfo.F_QUQY_COMPANY_Id, Right: ")", Logic: "and" }]
		}

		uni.navigateTo({
			url: `/pages/baseList/BaseList?FormId=${FormId}&isChoose=1&Group=${Group||''}&Name=请选择&R=5`,
			success: res => { res.eventChannel.emit('fun', [fun, null, FR]) }
		})

		// 回调方法
		let fun = (list) => {
			if (row) {
				// 🍕 子集里的
				row[Field][FieldSon] = list[0][IdKey]
				row[FieldName] = list[0][IdKeyName]

				if (Field == 'F_QUQY_Material') {
					// 🍕 查询物料库存单位，不传，后端自动带出
					kdApis.formQuery({
						data: {
							FormId: 'BD_UNIT',
							FieldKeys: 'FName,FNumber,FUNITID',
							FilterString: [{ "Left": "(", "FieldName": "FUNITID", "Compare": "=", "Value": list[0].FStoreUnitID, "Right": ")", "Logic": "and" }]
						}
					}).then(res => {
						if (res && res.length) {
							row.F_QUQY_UnitIDName = res[0].FName
						}
					})
				}
			} else {
				state.info.Data.Model[Field][FieldSon] = list[0][IdKey]
				state.info.Data.Model[FieldName] = list[0][IdKeyName]
				if (BringOther) {
					state.info.Data.Model[BringOther[0]] = list[0][BringOther[1]]
				}
			}

			// 🐟 选择养殖批次
			if (Field == 'F_QUQY_BreedingContract') {
				// 🍕 业务员
				state.info.Data.Model.F_QUQY_CustomerName = list[0]['F_UTPA_Base.FName']
				state.info.Data.Model.F_QUQY_Customer = {
					FNUMBER: list[0]['F_UTPA_Base.FNumber']
				}
			}
		}
	}
	const appendItem = () => {
		let obj = {
			F_QUQY_MaterialName: null,
			F_QUQY_Material: {
				FNUMBER: null
			},
			F_QUQY_UnitIDName: null,
			F_QUQY_RealQty: null,
			F_QUQY_Warehouse: state.F_QUQY_Warehouse,
			F_QUQY_WarehouseName: state.F_QUQY_WarehouseName,
			F_QUQY_UnitPrice: null,
			F_QUQY_Amount: null
		}
		state.info.Data.Model.FEntity.push(obj)
	}

	const longpress = (item, index) => {
		let msg = item.F_QUQY_MaterialName ? `请确认删除 [ ${item.F_QUQY_MaterialName} ] ？` : '请确认删除 ？'
		confirm(msg).then(() => {
			state.info.Data.Model.FEntity.splice(index, 1)
		}).catch(() => {})
	}

	const changeSwitch = (e) => {
		state.info.Data.Model.FEntity.forEach(it => {
			it.F_QUQY_RealQty = 0
			it.F_QUQY_Amount = 0
		})
	}

	const qtyChange = (row) => {
		if (row.F_QUQY_RealQty < 0 && !state.info.Data.Model.F_QUQY_DrugRepercussion) {
			row.F_QUQY_RealQty = 0
			row.F_QUQY_Amount = 0
			return
		}
		if (row.F_QUQY_UnitPrice) {
			// 解决js精度丢失
			row.F_QUQY_Amount = [(row.F_QUQY_RealQty * 100) * (row.F_QUQY_UnitPrice * 100)] / 10000
			// row.F_QUQY_Amount = row.F_QUQY_UnitPrice * row.F_QUQY_RealQty
		}
	}

	const priceChange = (row) => {
		// if (e.detail.value < 0) {
		// 	row.F_QUQY_UnitPrice = 0
		// 	row.F_QUQY_Amount = 0
		// 	return
		// }
		// if (row.F_QUQY_RealQty) {
		// 	row.F_QUQY_Amount = row.F_QUQY_RealQty * e.detail.value
		// }
		if(row.F_QUQY_UnitPrice < 0) {
			row.F_QUQY_UnitPrice = 0
			row.F_QUQY_Amount = 0
			return
		}
		if (row.F_QUQY_RealQty) {
			row.F_QUQY_Amount = [(row.F_QUQY_RealQty * 100) * (row.F_QUQY_UnitPrice * 100)] / 10000
		}
	}

	const save = async () => {
		await checkForm(state.info.Data.Model, state.rules)
		if (state.info.Data.Model.FEntity?.length == 0) return msg('请至少选择一种兽药！')

		let flag = false
		for (let item of state.info.Data.Model.FEntity) {
			if (item.F_QUQY_RealQty == 0) {
				flag = true
			}
		}
		if (flag) return msg('实发数量不能等于0！')

		let tepInfo = JSON.parse(JSON.stringify(state.info))
		tepInfo.Data.Model.F_QUQY_IsCompany = Number(tepInfo.Data.Model.F_QUQY_IsCompany)
		tepInfo.Data.Model.F_QUQY_DrugRepercussion = Number(tepInfo.Data.Model.F_QUQY_DrugRepercussion)
		kdApis.formSave(tepInfo).then((res) => {
			if (res) {
				msg('保存成功！')
				setTimeout(() => {
					uni.navigateBack()
				}, 300)
			}
		})
	}
	const getDetails = (Id) => {
		kdApis.formView({
			formId: 'QUQY_DrugOutbound',
			data: { Id }
		}).then((res) => {
			if (res) {
				let obj = {
					FId: res.Id,
					F_QUQY_DrugRepercussion: Boolean(Number(res.F_QUQY_DrugRepercussion)),
					F_QUQY_IsCompany: Boolean(Number(res.F_QUQY_IsCompany)),
					F_QUQY_Date: moment(res.F_QUQY_Date).format('YYYY-MM-DD'),
					F_QUQY_OrgId: {
						FNumber: res.F_QUQY_OrgId.Number
					},
					F_QUQY_OrgName: res.F_QUQY_OrgId?.Name[0].Value,
					F_QUQY_BreedingContract: {
						FNUMBER: res.F_QUQY_BreedingContract.Number
					},
					F_QUQY_BreedingContractName: res.F_QUQY_BreedingContract?.Name[0].Value,
					F_QUQY_Customer: {
						FNUMBER: res.F_QUQY_Customer.Number
					},
					F_QUQY_CustomerName: res.F_QUQY_Customer?.Name[0].Value,
					F_QUQY_Technician: {
						FSTAFFNUMBER: res.F_QUQY_Technician.Number
					},
					F_QUQY_TechnicianName: res.F_QUQY_Technician?.Name[0].Value,
					FEntity: res.FEntity.map(it => {
						return {
							F_QUQY_MaterialName: it.F_QUQY_Material?.Name[0].Value,
							F_QUQY_Material: {
								FNUMBER: it.F_QUQY_Material.Number
							},
							F_QUQY_UnitIDName: it.F_QUQY_UnitID?.Name[0].Value,
							F_QUQY_RealQty: it.F_QUQY_RealQty,
							F_QUQY_Warehouse: {
								FNUMBER: it.F_QUQY_Warehouse.Number
							},
							F_QUQY_WarehouseName: it.F_QUQY_WarehouseName,
							F_QUQY_UnitPrice: it.F_QUQY_UnitPrice,
							F_QUQY_Amount: it.F_QUQY_Amount
						}
					})
				}
				Object.assign(state.info.Data.Model, obj)
				state.loading = false
			}
		})
	}
	onLoad(async (query) => {
		state.memberInfo = uni.getStorageSync('memberInfo')
		// 🍕 仓库 技术员是当前人的
		kdApis.formQuery({
			data: {
				FormId: 'QUQY_VeterinaryDrugStock',
				FieldKeys: 'FName,FNumber',
				FilterString: [{ "Left": "(", "FieldName": "F_QUQY_Technician", "Compare": "=", "Value": state.memberInfo.Id, "Right": ")", "Logic": "and" }, { "Left": "(", "FieldName": "FDocumentStatus", "Compare": "=", "Value": "C", "Right": ")", "Logic": "and" }, { "Left": "(", "FieldName": "FForbidStatus", "Compare": "=", "Value": "A", "Right": ")", "Logic": "and" }]
			}
		}).then(res => {
			if (res && res.length) {
				state.F_QUQY_Warehouse = {
					FNUMBER: res[0].FNumber
				}
				state.F_QUQY_WarehouseName = res[0].FName
			}
		})
		if (query.Id) {
			state.pageName = '兽药出库编辑'
			getDetails(query.Id)
		} else {
			// 🍕 日期默认为当前日期
			state.info.Data.Model.F_QUQY_Date = moment(new Date()).format('YYYY-MM-DD')
			// 🍕 技术员默认当前人
			state.info.Data.Model.F_QUQY_Technician = {
				FSTAFFNUMBER: state.memberInfo.Number
			}
			state.info.Data.Model.F_QUQY_TechnicianName = state.memberInfo.Name[0].Value
			// 🍕 组织默认当前人组织
			state.info.Data.Model.F_QUQY_OrgId = {
				FNumber: state.memberInfo.F_QUQY_COMPANY.Number
			}
			state.info.Data.Model.F_QUQY_OrgName = state.memberInfo.F_QUQY_COMPANY.Name[0].Value

			state.loading = false
		}
	})
</script>
<style lang="scss" scoped>
	.card {
		position: relative;
		width: calc(100% - 60rpx);
		margin: 20rpx auto;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;

		.card-index {
			position: absolute;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 40rpx;
			height: 40rpx;
			padding-left: 10rpx;
			font-size: 24rpx;
			background: #409eff;
			color: #fff;
			clip-path: polygon(0 0, 0 40rpx, 10rpx 40rpx, 40rpx 10rpx, 40rpx 0);
		}
	}

	.btns {
		position: relative;

		.sum {
			position: absolute;
			right: 30rpx;
		}
	}
</style>
<style lang="scss" scoped>
	::v-deep .van-field {
		border-bottom: 1rpx solid #e9e9ea;
	}
	::v-deep .van-field__label {
		color: #000 !important;
	}
	::v-deep .van-field__control {
		text-align: right;
	}
	::v-deep .van-field__control::-webkit-input-placeholder {
	    color: gray;
	}
</style>